<?php

class Damages_Methods_Request_SendCarValueInquiry extends Damages_Methods_Request {

  /**
   *
   * @var int 
   */
  public $id;

  /**
   *
   * @var int 
   */
  public $estimatedCostId;

  public function __construct($params = null) {
    if ($params) {
      parent::__construct($params);
      $this->id = (int) $params->id;
      $this->estimatedCostId = (int) $params->estimatedCostId;
    }
  }

  public function process() {
    if (!Damages_Auth::getInstance()->checkPermission(array(Damages_Auth::PERMISSION_ADMIN, Damages_Auth::PERMISSION_LS)))
      throw new Damages_Exception_App(Damages_Codes::ACCESS_DENIED);
    $viewDir = Zend_Controller_Front::getInstance()->getModuleDirectory() . '/views/scripts/partials/';
    $carDamage = DamagesCarDamagesQuery::create()->findOneById($this->id);
    $dbTemplate = DamagesEmailTemplatesQuery::create()->findOneByCode('vq1');
    $templateContent = $dbTemplate->getTemplate();
    $view = new Zend_View();
    $view->setScriptPath($viewDir);
    $view->carDamage = $carDamage;
    $templateContent = nl2br($templateContent);
    foreach (Damages_Tags::getInstance()->getList() as $value) {
      if (preg_match(sprintf(Damages_Emails::TEMPLATE_REGEX, $value->code), $templateContent)) {
        $data = $view->render($value->code . '.phtml');
        $templateContent = preg_replace(sprintf(Damages_Emails::TEMPLATE_REGEX, $value->code), $data, $templateContent);
      }
    }
    $con = Propel::getConnection(Damages_Config::getInstance()->datasource);
    try {
      $con->beginTransaction();
      $emailId = Damages_Emails::addEmail($this->id, $dbTemplate->getId(), $templateContent, $carDamage->getCarData()->getDictBrands()->getContactEmail());
      $this->generatePriceInquiryFile($carDamage, $this->estimatedCostId, $emailId);
      $con->commit();
    } catch (Exception $exc) {
      $con->rollBack();
      throw $exc;
    }

    $response = new Damages_Methods_Response(true);
    return $response;
  }

  private function generatePriceInquiryFile($carDamage, $estimatedCostId, $emailId) {
    require_once 'PHPExcel.php';
    $estimatedCost = DamagesEstimatedBudgetsQuery::create()->findOneById($estimatedCostId);
    $inputFileName = APPLICATION_PATH . Damages_Config::getInstance()->xls->path . Damages_Config::getInstance()->xls->file;
    /** Load $inputFileName to a PHPExcel Object  * */
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
    $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A3', $carDamage->getCreated('Y-m-d'))
            ->setCellValue('B3', $carDamage->getCarData()->getComissionNo())
            ->setCellValue('C3', $carDamage->getCarData()->getVin())
            ->setCellValue('D3', $carDamage->getCarData()->getName())
            ->setCellValue('F3', $estimatedCost->getDiscountFlag() ? $estimatedCost->getDiscountPercentage() : 0);

    $resultDir = APPLICATION_PATH . Damages_Config::getInstance()->xls->tmp->path;
    if (!is_dir($resultDir))
      mkdir($resultDir, 0777, true);
    $resultPath = $resultDir . sprintf(Damages_Config::getInstance()->xls->tmp->file, $emailId);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save($resultPath);
  }

}